package org.feng.datasource;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态数据源配置
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2022年05月05日 14时56分
 */
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@Configuration
public class DynamicDataSourceConfig {


    @Primary
    @Bean
    public DataSource dynamicDataSource() {
        Map<Object, Object> dataSourceMap = DataSourcePool.getDataSourcePool();

        Map<String, DataSourceProperties> dataSourcePropertiesMap = DataSourcePool.getDatasourcePropertiesPool();
        dataSourcePropertiesMap.forEach((merchant, properties) -> dataSourceMap.put(merchant, DataSourcePool.buildDataSource(properties)));

        // 设置动态数据源
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(dataSourceMap.get(DataSourceConstant.MASTER));
        return dynamicDataSource;
    }

    @Primary
    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dynamicDataSource());
    }
}

